<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use think\facade\Env;
use think\helper\Str;
use app\model\Bazaar;
use OSS\OssClient;
use OSS\Core\OssException;
use \wapmorgan\UnifiedArchive\UnifiedArchive;

class Website extends Common
{

	/**
	 * 查询数据
	 *
	 * @return
	 */
	public function read(Request $request) {
		if($this->hasPermission($request->sessInfo, 'website:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$where = [];
		$limit = $request->param('limit/d', 20);
		$sort = $request->param('sort', 'id', 'trim');
		$order = $request->param('order', 'desc', 'trim');
		array_push( $where, ['companyId', '=', $request->sessInfo['companyId'] ] );
		$SiteName = $request->param('SiteName', '', 'trim');
		if($SiteName) {
			array_push( $where, ['SiteName', 'like',  "%{$SiteName}%" ] );
		}
		$DomainUrl = $request->param('DomainUrl', '', 'trim');
		if($DomainUrl) {
			array_push( $where, ['DomainUrl', 'like',  "%{$DomainUrl}%" ] );
		}
		$bazaar = $request->param('bazaar', '', 'trim');
		if($bazaar) {
			array_push( $where, ['bazaar', '=',  $bazaar ] );
		}
		$query = Db::name('cfg_site')->where($where)->order($sort, $order)->paginate($limit);
		$items = $query->items();
		foreach( $items as &$value ) {
			if($value['SiteSource']) {
				$value['isSiteSource'] = file_exists(public_path('storage')  . 'source' . DIRECTORY_SEPARATOR . $value['SiteSource']);
			} else {
				$value['isSiteSource'] = false;
			}
		}
		return ['code'=> 0, 'msg'=> '', 'count'=> $query->total(), 'data'=> $items ];
	}

	/**
	 * 更新数据
	 *
	 * @return
	 */
	public function update(Request $request) {
		if($this->hasPermission($request->sessInfo, 'website:update')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$param = $request->param();
		if( isset($param['state']) ) {
			$status = $request->param('status', '', 'trim');
			Db::name('cfg_site')
					->where('id', $param['state'])
					->where('companyId', $request->sessInfo['companyId'])
					->update([ 'status' => $status]);
			return ['code'=>0, 'msg'=>'操作成功'];
		}
		$id = $request->param('id', '', 'trim');
		$BaiduCode = $request->param('BaiduCode', '', 'trim');
		$SiteModel = $request->param('SiteModel', '', 'trim');
		$Copyright = $request->param('Copyright', '', 'trim');
		$DomainUrl = $request->param('DomainUrl', '', 'trim');
		$SiteName = $request->param('SiteName', '', 'trim');
		$SiteSource = $request->param('SiteSource', '', 'trim');
		$aPage = $request->param('aPage', '', 'trim');
		$abswitch = $request->param('abswitch', '', 'trim');
		$bPage = $request->param('bPage', '', 'trim');
		$bazaar = $request->param('bazaar', '', 'trim');
		$btAddress = $request->param('btAddress', '', 'trim');
		$btKey = $request->param('btKey', '', 'trim');
		$status = $request->param('status', '', 'trim');
		$Domains = $request->param('Domains', '', 'trim');
		$url = $request->param('url', '', 'trim');

    $DomainUrl = cloud_domain_format($DomainUrl);
		if( $DomainUrl == false) {
			return ['code'=>403, 'msg'=>'落地页无法识别!'];
		}

		Db::name('cfg_service_plan')
				->where('url', $DomainUrl)
				->where('companyId', $request->sessInfo['companyId'])
				->update( [ 'name' => $SiteName ]);

		Db::name('cfg_site')
				->where('id', $id)
				->where('companyId', $request->sessInfo['companyId'])
				->update( [ 'BaiduCode' => $BaiduCode, 'SiteModel' => $SiteModel, 'Domains' => $Domains, 'url' => $url, 'Copyright' => $Copyright, 'DomainUrl' => $DomainUrl, 'SiteSource' => $SiteSource,
				'aPage' => $aPage, 'abswitch' => $abswitch, 'bPage' => $bPage, 'bazaar' => $bazaar, 'btAddress' => $btAddress, 'SiteName' => $SiteName,
				'btKey' => $btKey, 'status' => $status ]);
		return ['code'=>0, 'msg'=>'操作成功'];
	}

	/**
	 * 修改Nginx配置文件
	 *
	 * @return
	 */
	public function saveNginx(Request $request) {
		if($this->hasPermission($request->sessInfo, 'website:update')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$id = $request->param('id', '', 'trim');
		if(empty($id)){
			return ['code'=> 403, 'msg'=> '站点ID不能为空, 请刷新页面重试!'];;
		}
		$nginxText = $request->param('nginxText', '', 'trim');
		if(empty($nginxText)){
			return ['code'=> 403, 'msg'=> 'Nginx数据异常, 请刷新页面重试!'];;
		}

		$site = Db::table('cfg_site')->where('companyId', $request->sessInfo['companyId'])->where('id', $id)->find();
		if(!isset($site['id'])){
			return ['code'=>403, 'msg'=>'落地页不存在, 操作失败!'];
		}

		if(empty($site['url'])) {
			return ['code'=>403, 'msg'=>'站点URL未配置, 操作失败!'];
		}

		if(empty($site['Domains'])) {
			return ['code'=>403, 'msg'=>'绑定域名未配置, 操作失败!'];
		}

		if(empty($site['btAddress'])) {
			return ['code'=>403, 'msg'=>'宝塔WebHook未配置, 操作失败!'];
		}

		if(empty($site['btKey'])) {
			return ['code'=>403, 'msg'=>'宝塔WebHook密匙未配置, 操作失败!'];
		}

		$abRadio = $request->param('abRadio', '', 'trim');
		if( $abRadio == 2 ) {
			if(empty($site['bPage'])) {
				return ['code'=>403, 'msg'=>'站点未设置B页面目录, 操作失败!'];
			}
			Db::name('cfg_site')->where('id', $site['id'])->update( [ 'abswitch' => 1 ]);
		}

		$nginxArray = [];
		$tempArray = explode("\n", $nginxText);
		foreach( $tempArray as $value ) {
			array_push($nginxArray, rtrim($value));
		}

		$static = public_path('static');
		$nginxFilename = md5($request->sessInfo['companyId'] . $site['DomainUrl']) . '.nginx';
		$nginxText = implode('\t\n', $nginxArray);
		$nginxText = str_replace("/", "\/", $nginxText);
		file_put_contents($static . $nginxFilename, $nginxText);

		$result = doGetRequest($site['btAddress'].'hook?access_key='.$site['btKey'].'&param=setNginx;'.$site['Domains'].';' .  'https://api.jiafen520.com/static/' . $nginxFilename );
		if(empty($result)){
			return ['code'=>403, 'msg'=>'网络通信异常, 操作失败!'];
		}

		$datacode = json_decode($result, true);
		if(!isset($datacode['code'])) {
			return ['code'=>403, 'msg'=>'网络通信异常, 操作失败!'];
		}

		if( $datacode['code'] == 0) {
			return ['code'=>403, 'msg'=>'宝塔KEY密匙错误, 操作失败!'];
		}

		return ['code'=>0, 'msg'=>'站点AB页指令发送成功.<br>具体是否操作成功, 请访问落地页验证。'];
	}

	/**
	 * 创建数据
	 *
	 * @return
	 */
	public function create(Request $request) {
		if($this->hasPermission($request->sessInfo, 'website:save')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$id = $request->param('id', '', 'trim');
		$SiteModel = $request->param('SiteModel', '', 'trim');
		$BaiduCode = $request->param('BaiduCode', '', 'trim');
		$Copyright = $request->param('Copyright', '', 'trim');
		$DomainUrl = $request->param('DomainUrl', '', 'trim');
		$SiteName = $request->param('SiteName', '', 'trim');
		$SiteSource = $request->param('SiteSource', '', 'trim');
		$aPage = $request->param('aPage', '', 'trim');
		$abswitch = $request->param('abswitch', '', 'trim');
		$bPage = $request->param('bPage', '', 'trim');
		$bazaar = $request->param('bazaar', '', 'trim');
		$btAddress = $request->param('btAddress', '', 'trim');
		$btKey = $request->param('btKey', '', 'trim');
		$status = $request->param('status', '', 'trim');
		$Domains = $request->param('Domains', '', 'trim');
		$url = $request->param('url', '', 'trim');
		if(empty($SiteName)) {
			return ['code'=>403, 'msg'=>'站点名称不能为空!'];
		}

		if(empty($DomainUrl)) {
			return ['code'=>403, 'msg'=>'落地页不能为空!'];
		}

    $DomainUrl = cloud_domain_format($DomainUrl);
		if( $DomainUrl == false) {
			return ['code'=>403, 'msg'=>'落地页无法识别!'];
		}

		$query = Db::table('cfg_site')->where('companyId', $request->sessInfo['companyId'])
			->where('DomainUrl', $DomainUrl)->value('DomainUrl');
		if(!empty($query)) {
			return ['code'=>403, 'msg'=>'落地页已存在!'];
		}

		Db::name('cfg_site')->insert([ 'companyId' => $request->sessInfo['companyId'], 'Domains' => $Domains, 'url' => $url, 'SiteModel' => $SiteModel, 'BaiduCode' => $BaiduCode, 'Copyright' => $Copyright, 'DomainUrl' => $DomainUrl,
		'SiteName' => $SiteName, 'SiteSource' => $SiteSource, 'aPage' => $aPage, 'abswitch' => $abswitch, 'bPage' => $bPage, 'bazaar' => $bazaar, 'btAddress' => $btAddress,
		'btKey' => $btKey, 'status' => $status, 'datatime' => date('Y-m-d H:i:s') ]);

		return ['code'=>0, 'msg'=>'操作成功'];
	}

	/**
	 * 删除数据
	 *
	 * @return
	 */
	public function delete(Request $request) {
		if($this->hasPermission($request->sessInfo, 'website:delete')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$param = $request->param();
		if( !isset($param['id']) ) {
			return ['code'=> 403, 'msg'=> '操作失败!'];
		}
		$beginTime = microtime(true);
		$delTemp = [];
		$explode = explode(',', $param['id']);
		foreach( $explode as $value ) {
			array_push($delTemp, Db::table('cfg_site')->where('id', $value)->where('companyId', $request->sessInfo['companyId'])->value('SiteName'));
			Db::table('cfg_site')->where('companyId', $request->sessInfo['companyId'])->where('id', $value)->delete();
		}
		unset($explode, $value);
		foreach( $delTemp as $value ) {
			if( $value ) {
				$endTime = microtime(true);
				$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
				$request->sessInfo['username'], round($endTime - $beginTime, 3), '用户管理', '删除用户['.$value.']', 0, json_encode($param));
			}
		}
		unset($delTemp, $value);
		return ['code'=> 0, 'msg'=> '删除成功!'];
	}

	/**
	 * 查询站点
	 *
	 * @return
	 */
	public function query(Request $request)
	{
		$url = $request->param('url', '', 'trim');
		if(empty($url)){
			return json(['code'=>0, 'data' => [], 'msg'=>'']);
		}

    $url = cloud_domain_format($url);
		if( $url == false) {
			return json(['code'=>0, 'data' => [], 'msg'=>'']);
		}

		$query = Db::table('cfg_site')->where('DomainUrl', $url)->value('DomainUrl');
		if(empty($query)){
			return json(['code'=>0, 'data' => [], 'msg'=>'']);
		}
		return json(['code'=>0, 'data' => [['url' => $query]], 'msg'=>'']);
	}

	/**
	 * 市场列表
	 *
	 * @return
	 */
	public function getBazaar(Request $request) {
		return json(['code'=>0, 'data'=> Bazaar::getList($request->sessInfo)]);
	}

	/**
	 * 上传源码
	 *
	 * @return
	 */
	public function upload(Request $request)
	{
		$files = $request->file();
		if (!isset($files['file'])) {
			return json(['code'=> 403, 'msg'=> '上传失败!']);
		}
		if(!is_object($files['file'])) {
			return json(['code'=> 403, 'msg'=> '上传失败!']);
		}
		$archive = UnifiedArchive::open($files['file']->getPathName());
		if(!is_object($archive)) {
			return json(['code'=> 403, 'msg'=> '上传失败, 权限不足!']);
		}
		if ($archive->isFileExists('index.html') === false ) {
			return json(['code'=> 403, 'msg'=> '上传失败, 没有检测到index.html文件!' ]);
		}
		$content = $archive->getFileContent('index.html');
		if( stripos($content, '</head>') === false ) {
			return json(['code'=> 403, 'msg'=> "上传失败, 没有检测到&lt;/head&gt;标签!" ]);
		}
		$content = $archive->getFileContent('index.html');
		if( stripos($content, '</body>') === false ) {
			return json(['code'=> 403, 'msg'=> "上传失败, 没有检测到&lt;/body&gt;标签!" ]);
		}
		if( stripos($content, 'san_cloud.js') !== false ) {
			return json(['code'=> 403, 'msg'=> '上传失败, 请先去掉客服统计代码!' ]);
		}
		if( stripos($content, 'cnzz.com') !== false ) {
			return json(['code'=> 403, 'msg'=> '上传失败, 请先去掉CNZZ统计代码!' ]);
		}
		if( stripos($content, 'hm.baidu.com') !== false ) {
			return json(['code'=> 403, 'msg'=> '上传失败, 请先去掉百度统计代码!' ]);
		}
    try {
			validate([
				'file' => [
					'fileSize' => 15728640,
					'fileExt' => 'zip',
				]
			])->check($files);
			$fileName = hash_file('sha1', $files['file']->getPathName());
			$savename = \think\facade\Filesystem::disk('public')->putFileAs( 'source', $files['file'], $fileName);
			if($savename){
				return json(['code'=> 0, 'msg'=> '源码上传成功!', 'url' => $fileName ]);
			}
    } catch (\think\exception\ValidateException $e) {
			return json(['code'=> 403, 'msg'=> $e->getMessage()]);
    }
		return json(['code'=> 403, 'msg'=> '上传失败!']);
	}

	/**
	 * 上传方法
	 *
	 * @return
	 */
	protected function uploadFile($object, $filePath)	{
		$result = ['code'=> 403, 'msg'=> '上传失败!'];
		if (file_exists($filePath) == false) {
			return $result;
		}
		$bucket = Env::get('aliyun.bucket', 'bucket');
		if ($bucket == 'bucket') {
			return $result;
		}
		$endpoint = Env::get('aliyun.endpoint', 'endpoint');
		if ($endpoint == 'endpoint') {
			return $result;
		}
		$accessKeyId = Env::get('aliyun.accesskeyid', 'accesskeyid');
		if ($accessKeyId == 'accessKeyId') {
			return $result;
		}
		$accessKeySecret = Env::get('aliyun.accesskeysecret', 'accesskeysecret');
		if ($accessKeySecret == 'accessKeySecret') {
			return $result;
		}
		$originaldomain = Env::get('aliyun.originaldomain', 'originaldomain');
		if ($originaldomain == 'originaldomain') {
			return $result;
		}
		$domain = Env::get('aliyun.domain', 'domain');
		if ($domain == 'domain') {
			return $result;
		}
		$archive = UnifiedArchive::open($filePath);
		if(!is_object($archive)) {
			return json(['code'=> 403, 'msg'=> '上传失败, 权限不足!']);
		}

		if ($archive->isFileExists('index.html') === false ) {
			return ['code'=> 403, 'msg'=> '上传失败, 没有检测到index.html文件!' ] ;
		}

		$body = $archive->getFileContent('index.html');
		if( stripos($body, '</head>') === false ) {
			return ['code'=> 403, 'msg'=> "上传失败, 没有检测到&lt;/head&gt;标签!" ];
		}

		if( stripos($body, 'san_cloud.js') !== false ) {
			return ['code'=> 403, 'msg'=> '上传失败, 请先去掉客服统计代码!' ];
		}

		if( stripos($body, 'cnzz.com') !== false ) {
			return ['code'=> 403, 'msg'=> '上传失败, 请先去掉CNZZ统计代码!' ];
		}

		if( stripos($body, 'hm.baidu.com') !== false ) {
			return ['code'=> 403, 'msg'=> '上传失败, 请先去掉百度统计代码!' ];
		}

		try {
			$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
			$result = $ossClient->uploadFile($bucket, $object, $filePath);
			if (isset($result['info']['http_code']) && $result['info']['http_code'] == 200) {
				$result = ['code'=> 0, 'msg'=> '源码上传成功!', 'url' => str_replace($originaldomain, $domain, $result['info']['url'])];
			}
		} catch (OssException $e) {
			$result = ['code'=> 403, 'msg'=>$e->getMessage()];
		}
		return $result;
	}

}
